package primary.String;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Elephas
 * @Date 2022/1/8
 **/
public class IsAnagram {
    public static void main(String[] args) {
        final String TEST01_1 = "rat";
        final String TEST01_2 = "car";
        IsAnagram3(TEST01_1,TEST01_2);
    }

    /*
        解法一：用一个hashmap，记录s1中单词频率，再遍历s2，每遍历一个字符对应频率减少1。最后如果hashmap中所有频率均为0，则返回true，否则返回false
     */
    public boolean isAnagram(String s1, String s2) {
        Map<Character, Integer> map = new HashMap<>();
        if (s1.length() != s2.length())
            return false;
        for (int i = 0; i < s1.length(); i++) {
            char temp = s1.charAt(i);
            if (map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            } else {
                map.put(temp, 1);
            }
        }

        for (int i = 0; i < s2.length(); i++) {
            char temp2 = s2.charAt(i);
            if (map.containsKey(temp2)) {
                map.put(temp2, map.get(temp2) - 1);
            } else {
                map.put(temp2, -1);
            }
        }
        boolean flag = true;
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() != 0) {
                flag = false;
                break;
            }
        }

        return flag;

    }

    /*
        数组实现哈希
     */
    public boolean IsAnagram2(String s1, String s2) {
        int count = 0;
        char[] s1ToChars = s1.toCharArray();
        char[] s2ToChars = s2.toCharArray();
        int[] chars = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            chars[s1ToChars[i] - 'a']++;
            count++;
        }
        for (int i = 0; i < s2.length(); i++) {
            if (chars[s2ToChars[i] - 'a'] > 0) {
                count--;
                chars[s2ToChars[i] - 'a']--;
            } else {
                count++;
            }
        }
        return count == 0 ? true : false;
    }

    /*
        修改一下写法，变量命名规范,官方答案
     */
    public static boolean IsAnagram3(String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        int[] table = new int[26];
        //table 初始化
        for (int i = 0; i < s1.length(); i++) {
            table[s1.charAt(i)-'a']++;
        }
        for (int i = 0; i < s2.length(); i++) {
            if(table[s2.charAt(i)-'a']<=0){
                return false;
            }else {
                table[s2.charAt(i)-'a']--;
            }
        }
        return true;
    }

}